﻿using DevelopAssistant.Core.ToolBar;
using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Controls;
using ICSharpCode.WinFormsUI.Docking;
using NORM.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace DevelopAssistant.Core.DBMS
{
    public partial class AddTableDocument : DockContent
    {
        int max_rowIndex = 0;
        string table = string.Empty;
        DataBaseServer server = null;

        private ComboBox DropDownDataTypes = new ComboBox();
        protected MainForm OwnerForm { get; set; }

        public AddTableDocument()
        {
            InitializeComponent();
            InitializeControls();
        }

        public AddTableDocument(NTreeNode node, DataBaseServer dataBaseServer, MenuBar menuBar)
            : this()
        {
            server = dataBaseServer;
            this.txtTableName.Text = table;
            BindDataTypes(server.ProviderName);
        }

        private void GetTableColumns()
        {
            DataTable dv = new DataTable();
            dv.Columns.Add(new DataColumn("序号", typeof(Int32)));
            dv.Columns.Add(new DataColumn("名称", typeof(String)));
            dv.Columns.Add(new DataColumn("数据类型", typeof(String)));
            dv.Columns.Add(new DataColumn("长度", typeof(String)));
            dv.Columns.Add(new DataColumn("主键标识", typeof(String)));
            dv.Columns.Add(new DataColumn("允许为空", typeof(String)));
            dv.Columns.Add(new DataColumn("自增标识", typeof(String)));
            dv.Columns.Add(new DataColumn("描述", typeof(String)));
            dv.Columns.Add(new DataColumn("全标识", typeof(String)));

            this.dgv_design.DataSource = dv.DefaultView;
        }

        public void InitializeControls()
        {
            this.dgv_design.Controls.Add(DropDownDataTypes);
            this.DropDownDataTypes.Visible = false;
            this.DropDownDataTypes.BackColor = Color.White;
            this.DropDownDataTypes.DropDownStyle = ComboBoxStyle.DropDownList;
            this.panel1.TopBlackColor = Color.WhiteSmoke;
            this.panel1.BottomBlackColor = SystemColors.Control;
            this.DropDownDataTypes.SelectedValueChanged += DropDownDataTypes_SelectedValueChanged;             
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    DataGridViewCell cell = dgv_design.Rows[e.RowIndex].Cells[e.ColumnIndex];//dataGridView1.CurrentCell; //
                    Rectangle rect = dgv_design.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, false);
                    DropDownDataTypes.Left = rect.X;
                    DropDownDataTypes.Top = rect.Y;
                    DropDownDataTypes.Width = rect.Width;
                    DropDownDataTypes.Height = rect.Height;
                    DropDownDataTypes.Visible = true;

                    DropDownDataTypes.SelectedItem = cell.Value;

                    if (cell.RowIndex == max_rowIndex && (cell.Value + "") == "")
                    {
                        cell.Value = (string)DropDownDataTypes.SelectedItem;
                    }

                }
                else if (e.ColumnIndex == 4)
                {
                    DropDownDataTypes.Visible = false;
                }
                else
                {
                    DropDownDataTypes.Visible = false;
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                var value = dgv_design.Rows[e.RowIndex].Cells[4].Value;
                if (value != null && value != DBNull.Value)
                {
                    if (value.ToString().Contains("Pk"))
                    {
                        Graphics g = e.Graphics;
                        e.Graphics.DrawImage(this.imageList1.Images[0], e.RowBounds.Left + 18, e.RowBounds.Top + (e.RowBounds.Height - 16) / 2, 16f, 16f);//绘制图标
                    }
                }
            }
        }

        private void BindDataTypes(string ProviderName)
        {
            string DataBaseTypes = "Sql";
            switch (ProviderName)
            {
                case "System.Data.SQL":
                case "System.Data.Sql":
                    DataBaseTypes = "Sql";
                    break;
                case "System.Data.Sqlite":
                    DataBaseTypes = "Sqlite";
                    break;
                case "System.Data.PostgreSql":
                    DataBaseTypes = "PostgreSql";
                    break;
            }

            string path = Application.StartupPath + "\\" + "DataBaseDataTypes.xml";
            if (System.IO.File.Exists(path))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNodeList list = xmldoc.SelectSingleNode(string.Format("{0}{1}{2}",
                    "//", DataBaseTypes, "DataBase")).ChildNodes;

                foreach (XmlNode li in list)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem();
                    item.Text = li.Attributes["DataType"].Value + "";
                    this.DropDownDataTypes.Items.Add(item.Text);
                }

            }
            else
            {
                MessageBox.Show("DataBaseDataTypes.xml文件不存在");
            }


        }

        private void DropDownDataTypes_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                ComboBox cbox = (ComboBox)sender;
                DataGridViewCell DCell = dgv_design.CurrentCell;
                if (DCell != null)
                {
                    dgv_design.CurrentCell.Value = cbox.Text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgv_design_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex > -1 && e.ColumnIndex == -1)
                {
                    Rectangle rect = dgv_design.GetCellDisplayRectangle(1, e.RowIndex, true);
                    Point MousePt = new Point(e.X, e.Y);
                    MousePt.Offset(rect.X - dgv_design.RowHeadersWidth, rect.Y);
                    dgv_design.ClearSelection();
                    dgv_design.Rows[e.RowIndex].Selected = true;
                    contextMenuStrip1.Show(dgv_design, MousePt);
                }
            }
        }

        private void btnApplyOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtTableName.Text))
            {
                MessageBox.Show("请输入表名");
                return;
            }

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("ColumnName", typeof(string)));
            dt.Columns.Add(new DataColumn("TypeName", typeof(string)));
            dt.Columns.Add(new DataColumn("CisNull", typeof(string)));
            dt.Columns.Add(new DataColumn("Length", typeof(string)));

            using (var db = Utility.GetAdohelper(server))
            {
                try
                {
                    foreach (DataGridViewRow row in dgv_design.Rows)
                    {
                        string name = row.Cells[1].Value + "";
                        string typename = row.Cells[2].Value + "";
                        string len = row.Cells[3].Value + "";
                        string pk = row.Cells[4].Value + "";
                        string isnull = row.Cells[5].Value + "";
                        string identity = row.Cells[6].Value + "";

                        string cisnull = string.Empty;

                        if (isnull.Equals("true",
                            StringComparison.OrdinalIgnoreCase))
                        {
                            isnull = "NULL";
                        }
                        else
                        {
                            isnull = "NOT NULL";
                        }

                        cisnull += isnull;

                        if (pk.ToLower().Contains("pk"))
                        {
                            cisnull += ",pk";
                        }

                        if (identity.Contains("identity"))
                        {
                            cisnull += ",identity";
                        }

                        DataRow dr = dt.NewRow();
                        dr["ColumnName"] = name;
                        dr["TypeName"] = typename;
                        dr["CisNull"] = cisnull;
                        dr["Length"] = len;

                        dt.Rows.Add(dr);

                    }

                    string sql = DevelopAssistant.Service.
                        CreateTable.ToSnippetCode(txtTableName.Text, server, dt);

                    db.Execute(CommandType.Text, sql, null);

                    MessageBox.Show("添加成功");

                    this.Close();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 添加列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = 0;
            if (dgv_design.SelectedRows.Count > 0)
                selectedRowIndex = dgv_design.SelectedRows[0].Index;
            else
                selectedRowIndex = dgv_design.Rows.Count;

            DataTable dt = (dgv_design.DataSource as DataView).Table;
            DataRow row = dt.NewRow();
            row[5] = true;
            dt.Rows.InsertAt(row, selectedRowIndex);
        }

        private void 删除列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in dgv_design.SelectedRows)
                {
                    dgv_design.Rows.Remove(row);
                }
            }
        }

        private void 上移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                DataTable dt = ((DataView)dgv_design.DataSource).Table;
                int index = dgv_design.SelectedRows[0].Index;

                if (index > -1)
                {
                    int preIndex = index - 1;
                    int nextIndex = index + 1;

                    if (preIndex < 0)
                        preIndex = 0;

                    if (nextIndex > dt.Rows.Count - 1)
                        nextIndex = dt.Rows.Count - 1;

                    if (index != preIndex)
                    {
                        DataTable newdt = dt.Clone();
                        newdt.Rows.Clear();

                        DataRow dr1 = dt.Rows[index];
                        DataRow dr2 = dt.Rows[preIndex];

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i == index)
                            {
                                newdt.ImportRow(dr2);
                            }
                            else if (i == preIndex)
                            {
                                newdt.ImportRow(dr1);
                            }
                            else
                            {
                                newdt.ImportRow(dt.Rows[i]);
                            }
                        }

                        dgv_design.DataSource = newdt.DefaultView;

                        SetDataGridViewSeletedRow(preIndex);

                        dgv_design.Invalidate();

                    }
                }
            }

        }

        private void 下移ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (dgv_design.SelectedRows.Count > 0)
            {
                DataTable dt = ((DataView)dgv_design.DataSource).Table;
                int index = dgv_design.SelectedRows[0].Index;

                if (index > -1)
                {
                    int preIndex = index - 1;
                    int nextIndex = index + 1;

                    if (preIndex < 0)
                        preIndex = 0;

                    if (nextIndex > dt.Rows.Count - 1)
                        nextIndex = dt.Rows.Count - 1;

                    if (index != nextIndex)
                    {
                        DataTable newdt = dt.Clone();
                        newdt.Rows.Clear();

                        DataRow dr1 = dt.Rows[index];
                        DataRow dr2 = dt.Rows[nextIndex];

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i == index)
                            {
                                newdt.ImportRow(dr2);
                            }
                            else if (i == nextIndex)
                            {
                                newdt.ImportRow(dr1);
                            }
                            else
                            {
                                newdt.ImportRow(dt.Rows[i]);
                            }
                        }

                        dgv_design.DataSource = newdt.DefaultView;

                        SetDataGridViewSeletedRow(nextIndex);

                        dgv_design.Invalidate();

                    }
                }
            }
        }

        private void 设为主键ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                dgv_design.EndEdit();

                var cisnull = dgv_design.SelectedRows[0].Cells[5].Value;
                if (cisnull != null && cisnull != DBNull.Value && Boolean.Parse(cisnull + ""))
                {
                    MessageBox.Show("设为主键的列不能允许为空");
                    return;
                }

                foreach (DataGridViewRow row in dgv_design.Rows)
                {
                    var value = row.Cells[4].Value + "";
                    if (value.ToString().Contains("Pk") && row.Index == dgv_design.SelectedRows[0].Index)
                        return;

                    if (value.ToString().Contains("Pk"))
                    {
                        row.Cells[4].Value = value.ToString().Replace("Pk", "");
                    }
                    else if (row.Index == dgv_design.SelectedRows[0].Index)
                    {
                        row.Cells[4].Value += "Pk" + value;
                    }
                }

                ((dgv_design.DataSource) as DataView).Table.AcceptChanges();

                dgv_design.Invalidate();
            }
        }

        private void SetDataGridViewSeletedRow(int index)
        {
            dgv_design.ClearSelection();
            dgv_design.Rows[index].Selected = true;
        }

        private void AddTableDocument_Load(object sender, EventArgs e)
        {
            OwnerForm = (MainForm)this.Owner;
            GetTableColumns();
        }

    }
}
